<template>
  <div class="scop">
    <div class="btn connect" @click="connectBtnClick">连接</div>
    <div class="btn discon" @click="disConnectBtnClick">断开</div>
    <div class="show">{{data}}</div>
  </div>
</template>

<script>
export default {
  name: 'scop',
  data () {
    return {
      path: "ws://192.168.3.13:3000",
      socket: "",
      data: '',
    }
  },
  mounted () {
    // 初始化
    // this.ws_init();
  },
  methods: {
    // 连接按钮点击事件
    connectBtnClick(){
      this.ws_init();
    },
    // 断开连接
    disConnectBtnClick(){
      this.socket.close();
    },
    ws_init: function () {
      if(typeof(WebSocket) === "undefined"){
        alert("您的浏览器不支持socket")
      }else{
        // 实例化socket
        this.socket = new WebSocket(this.path)
        // 监听socket连接
        this.socket.onopen = this.open
        // 监听socket错误信息
        this.socket.onerror = this.error
        // 监听socket消息
        this.socket.onmessage = this.getMessage
      }
    },
    open: function () {
      console.log("socket连接成功");
      this.socket.send("index");
    },
    error: function () {
      console.log("连接错误")
    },
    getMessage: function (msg) {
      // console.log(msg.data);
      this.data = msg.data;
    },
    send: function () {
      this.socket.send(params)
    },
    close: function () {
      console.log("socket已经关闭")
    }
  }
}
</script>

<style scoped lang="scss">
.scop{
  text-align: center;
  .btn{
    width: 120px;
    height: 40px;
    margin: 30px 10px;
  }
  .connect{
    color: red;
  }
  // .show
}
</style>
